<?php

namespace app\admin\controller\kuerp;

use app\admin\library\Auth;
use app\admin\model\Admin;
use app\api\controller\kuerp\order\Index;
use app\common\controller\Backend;
use think\Db;
use Exception;
use think\Session;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 * 订货单
 *
 * @icon fa fa-circle-o
 */
class UserOrder extends Backend
{
    protected $noNeedRight = ['checkPurchase','getSuppliers','getUnit','formatInfo','formatInfo2','getBranch','getTime'];
    /**
     * GoodsPurchase模型对象
     * @var \app\admin\model\kuerp\UserOrder
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $setData = (new Goods())->getSetData();
        $this->assign('set', $setData['setList']);
        $this->assignconfig('set',$setData['setList']);
        $this->assign('nowmenu', $setData['nowmenu']);

        $this->model = new \app\admin\model\kuerp\UserOrder;
        $this->view->assign("StatusList", $this->model->getStatusList());
        $this->view->assign("payStatusList", $this->model->getPayStatusList());

        $pay_status = Db::name('kuerp_user_config')->where(['name'=>'pay_status'])->value('value');
        $driver = Db::name('kuerp_driver')->where(['status'=>'1'])->field('name,id')->select();
        $del = (new Auth())->check($setData['nowmenu'].'/del');
        $this->assignconfig('del_status',$del);
        $this->assignconfig('pay_status',$pay_status);
        $this->assignconfig('driver_list',$driver);

        $edit = (new Auth())->check($setData['nowmenu'].'/edit');
        $print_config = ROOT_PATH.'/application/extra/prints.php';
        if(file_exists($print_config) && $edit){
            $this->assignconfig('prints_status',true);
        }else{
            $this->assignconfig('prints_status',false);
        }
    }

    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $lists = [];
            foreach ($list as $list_k=>$list_v){
                $sales_id = Db::name('kuerp_user_ordersale')->where(['order_id'=>$list_v['id']])->value('sales_id');

                if($list_v['diver_type']==2 && !empty($list_v['store_id'])){
                    $address = Db::name('kuerp_address')->where(['id'=>$list_v['store_id']])->value('detail_address');
                    $list_v['address'] = $address.'(自提)';
                }
                $list_v['diver_name'] = Db::name('kuerp_driver')->where(['id'=>$list_v['diver_id']])->value('name');
                $goods_list = Db::name('kuerp_user_orderinfo')->where(['order_id'=>$list_v['id']])
                    ->select();
                foreach ($goods_list as $goods_list_k=>$goods_list_v){
                    $goods_code = Db::name('kuerp_goods')->where(['id'=>$goods_list_v['goods_id']])->value('goods_code');
                    $lists[] = [
                        'id' => $list_v['id'],
                        'sales_id' => $sales_id,
                        'name' => $list_v['name'],
                        'phone' => $list_v['phone'],
                        'address' => $list_v['address'],
                        'order_num' => $list_v['order_num'],
                        'order_price' => $list_v['order_price'],
                        'status' => $list_v['status'],
                        'createtime' => $list_v['createtime'],
                        'goods_code' => $goods_code,
                        'goods_name' => $goods_list_v['goods_name'],
                        'goods_image' => $goods_list_v['goods_image'],
                        'unit_name' => $goods_list_v['unit_name'],
                        'attr_name' => $goods_list_v['attr_name'],
                        'number' => $goods_list_v['number'],
                        'price' => $goods_list_v['price'],
                        'money' => $goods_list_v['money'],
                        'pay_status' => $list_v['pay_status'],
                        'diver_type' => $list_v['diver_type'],
                        'diver_id' => $list_v['diver_id'],
                        'diver_name' => $list_v['diver_name'],
                    ];
                }
            }
            $result = array("total" => $list->total(), "rows" => $lists);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 审核
     */
    public function examine($ids = null){
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    (new Index())->Message('sh',$v['order_num']);
                    $count += $this->model->where(['id'=>$v['id']])->update(['status'=>'2','updatetime'=>time()]);
                }
                Db::commit();
            }catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('审核失败'));
            }
        }
        $this->error(__('请选择要审核的数据', 'ids'));
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 发货
     */
    public function deliver($ids = null){
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $diver_id = input("diver_id");
            $list = $this->model->where($pk, 'in', $ids)->select();
            foreach ($list as $k => $v) {
                switch ($v['status']){
                    case 0:
                        $this->error($v['order_num'].'未审核，不可发货');
                        break;
                    case 2:
                        $sales_id = Db::name('kuerp_user_ordersale')->where(['order_id'=>$v['id']])->value('sales_id');
                        if(empty($sales_id)){
                            $this->error($v['order_num'].'未生成销货单，不可发货');
                        }
                        $pay_status = Db::name('kuerp_user_config')->where(['name'=>'pay_status'])->value('value');
                        if($pay_status==1 && $v['pay_status']!=1){
                            $this->error($v['order_num'].'未支付，不可发货');
                        }
                        break;
                    case 3:
                        $this->error($v['order_num'].'已发货，不可重复发货');
                        break;
                    case 4:
                        $this->error($v['order_num'].'已收货，不可重复发货');
                        break;
                    default:
                        $this->error($v['order_num'].'状态异常，不可发货');
                        break;
                }
            }
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    (new Index())->Message('fh',$v['order_num']);
                    $data = [];
                    $data['status'] = '3';
                    if($v['diver_type']==1){
                        $data['diver_id'] = (int)$diver_id;
                    }
                    $count += $this->model->where(['id'=>$v['id']])->update($data);
                }
                Db::commit();
            }catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('审核失败'));
            }
        }
        $this->error(__('请选择要审核的数据', 'ids'));
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            }catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('删除失败'));
            }
        }
        $this->error(__('请选择要删除的数据', 'ids'));
    }

}
